# -*- coding: utf-8 -*-
'''
    :file: mails.py
    :author: -Farmer
    :url: https://blog.farmer233.top
    :date: 2021/02/14 15:27:41
'''
from flask import current_app, render_template
from flask_mail import Message
from threading import Thread
# 
from app.extensions import mail

# 发送邮件主体（异步发送）
def _send_async_mail(app, message):
    with app.app_context():
        mail.send(message)

# 发送邮件
def send_mail(subject, to, template, **kwargs):
    message = Message(
        subject=current_app.config['MCLOUD_MAIL_SUBJECT_PREFIX'] + subject, recipients=[to])
    message.body = render_template(template + ".txt", **kwargs)
    message.html = render_template(template + ".html", **kwargs)
    app = current_app._get_current_object()
    thr = Thread(target=_send_async_mail, args=[app, message])
    thr.start()
    return thr

# 发送重置密码邮件
def send_reset_password_email(user, token):
    send_mail(subject="Password Reset", to=user.email,
              template="reset_password", user=user, token=token)

# 发送忘记密码邮件
def send_forget_password_code_mail(user, code):
    send_mail(
        subject="Password Reset",
        to=user.email,
        template="reset_password",
        user=user,
        code=code
    )
